#!/bin/bash

# 函数定义######################################################################
push_all_branches_and_tags() {
    if [ -z "$1" ]; then
        echo "push_all_branches_and_tags: missing remote"
        return 1
    fi

    echo "Pushing all $(str_highlight branches) to remote \`$(str_highlight $1)' ..."
    git push --all "$1"
    echo

    echo "Pushing all $(str_highlight tags) to remote \`$(str_highlight $1)' ..."
    git push --tags "$1"
    echo
}

# 初始化全局数据################################################################
GPF_SUB_CMD_NAME=$(basename $0)
################################################################################

# Bash里使用getopts解析非选项参数: http://9.douban.com/subject/9127110/

declare -a NOA # Array used to store non-option argument
 
while [ $# -ne 0 ]
do
    # if OPTIND > $#+1, getopts will not change OPTIND's value,so set it to 0
    OPTIND=0
    while getopts : opt
    do
        case $opt in
            \?)
                echo "Invalid option -- $OPTARG"
                echo "Usage: $GPF_PROC_NAME $GPF_SUB_CMD_NAME [remote ...]"
                exit 0
                ;;
        esac
    done
 
    # if getopts find a non-option argument
    # it will stop parsing and return OPTIND
    # as index to the first non-option argument
    # 
    # if getopts doesn't find any non-option argument
    # it will set OPTIND=$#+1
    if [ $OPTIND -ne $(($#+1)) ]
    then
        shift $(($OPTIND-1))
        # This is just my favorate way to append element to an array in shell.
        # Feel free to change it
        NOA=(`echo ${NOA[*]}` $1)
        shift
    else
        break; # getopts doesn't find any non-option argument
    fi
done

################################################################################

declare -a ret

GPF_GIT_DIR=$(git rev-parse --git-dir)
ret=$?
if [[ $ret != 0 ]]; then
    exit $ret
fi

GPF_CONFIG_FILE_PATH="$GPF_GIT_DIR/$GPF_CONFIG_FILE"

declare -a rem_list
declare -a rem

if [[ ${#NOA} == 0 ]]; then
    rem_list=$(git config -f "$GPF_CONFIG_FILE_PATH" --get-all remotes.push)
    
    ret=$?
    if [[ $ret != 0 ]]; then
        exit $ret
    fi
else
    rem_list="${NOA[*]}"
fi

for rem in $rem_list; do
    push_all_branches_and_tags "$rem"
    
    ret=$?
    if [[ $ret != 0 ]]; then
        exit $ret
    fi
done
